<template>
  <s-clean-layout title="借钱管理" navbar="normal">
    <view class="borrow-container">
      <!-- 统计卡片 -->
      <view class="summary-container">
        <view class="summary-card">
          <view class="summary-item">
            <text class="amount-value">{{ totalBorrow }}</text>
            <text class="amount-label">待收金额</text>
          </view>
          <view class="summary-divider"></view>
          <view class="summary-item">
            <text class="amount-value">{{ totalLend }}</text>
            <text class="amount-label">待还金额</text>
          </view>
        </view>
      </view>
      
      <!-- 借钱记录列表 -->
      <scroll-view scroll-y class="borrow-list">
        <view 
          class="borrow-item" 
          v-for="(item, index) in borrowRecords" 
          :key="index"
          @tap="viewRecordDetail(item.id)"
        >
          <view class="person-avatar">
            <image v-if="item.avatarUrl" :src="item.avatarUrl" mode="aspectFill" class="avatar-image"></image>
            <text v-else>{{ item.contactName.charAt(0) }}</text>
          </view>
          <view class="borrow-info">
            <view class="person-name">{{ item.contactName }}</view>
            <view class="borrow-date">{{ item.borrowDate }}</view>
            <view class="event-name" v-if="item.eventName">{{ item.eventName }}</view>
          </view>
          <view class="borrow-amount">
            <view class="amount-container">
              <text :style="{ color: getTransactionTypeColor(item.transactionType) }">
                {{ getTransactionTypeText(item.transactionType) }}{{ item.amount }}
              </text>
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>
            </view>
            <view class="borrow-status" :style="{ color: getStatusColor(item.status) }">
              {{ getStatusText(item.status) }}
            </view>
          </view>
        </view>
      </scroll-view>
      
      <!-- 添加悬浮按钮 -->
      <view class="add-button" @tap="addBorrowRecord">
        <uni-icons type="plusempty" size="24" color="#FFFFFF"></uni-icons>
      </view>
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import BorrowApi from '@/pages/money/api/borrow';

// 统计数据
const totalBorrow = ref('0');
const totalLend = ref('0');

// 借钱记录数据
const borrowRecords = ref([]);

// 页面加载时获取数据
onMounted(() => {
  fetchBorrowRecords();
});

// 页面显示时刷新数据
onShow(() => {
  fetchBorrowRecords();
});

// 获取借钱记录
const fetchBorrowRecords = async () => {
  try {
    const response = await BorrowApi.queryBorrowRecords();
    
    if (response.code === 0 && response.data) {
      // 处理返回的数据
      borrowRecords.value = response.data.map(item => ({
        id: item.id,
        contactName: item.contactName,
        contactId: item.contactId,
        amount: item.amount,
        borrowDate: formatDate(item.borrowDate),
        repaymentDate: item.repaymentDate ? formatDate(item.repaymentDate) : '',
        transactionType: item.transactionType, // IN-收入，OUT-支出
        eventName: item.eventName,
        accountType: item.accountType,
        status: item.status, // 0-未还款，1-部分还款，2-已还清，3-已逾期
        remark: item.remark,
        imageUrls: item.imageUrls
      }));
      
      // 计算总金额
      const borrowTotal = borrowRecords.value
        .filter(item => item.transactionType === 'OUT' && item.status !== 2)
        .reduce((sum, item) => sum + (Number(item.amount) || 0), 0);
      
      const lendTotal = borrowRecords.value
        .filter(item => item.transactionType === 'IN' && item.status !== 2)
        .reduce((sum, item) => sum + (Number(item.amount) || 0), 0);
      
      totalBorrow.value = borrowTotal.toString();
      totalLend.value = lendTotal.toString();
    } else {
      uni.showToast({
        title: response.msg || '获取借钱记录失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取借钱记录失败:', error);
    uni.showToast({
      title: '获取借钱记录失败',
      icon: 'none'
    });
  }
};

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未还款',
    1: '部分还款',
    2: '已还清',
    3: '已逾期'
  };
  return statusMap[status] || status;
};

// 获取交易类型文本
const getTransactionTypeText = (type) => {
  return type === 'IN' ? '借入' : '借出';
};

// 获取交易类型颜色
const getTransactionTypeColor = (type) => {
  return type === 'IN' ? '#5a9cf8' : '#ff6b6b';
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    0: '#ff6b6b', // 未还款
    1: '#ff9800', // 部分还款
    2: '#67c23a', // 已还清
    3: '#f56c6c'  // 已逾期
  };
  return colorMap[status] || '#666';
};

// 查看记录详情
const viewRecordDetail = (id) => {
  sheep.$router.go('/pages/money/borrow-edit', {
    id: id
  });
};

// 添加借钱记录
const addBorrowRecord = () => {
  sheep.$router.go('/pages/money/borrow-edit', {
    isAdd: true
  });
};

// 移除不再需要的goBack方法
// const goBack = () => {
//   uni.navigateBack();
// };
</script>

<style lang="scss" scoped>
.borrow-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  padding-top: 20rpx; /* 添加顶部间距 */
}

/* 移除原有的导航栏样式 */
.nav-bar {
  display: none;
}

.back-btn, .add-btn {
  display: none;
}

.page-title {
  display: none;
}

.summary-container {
  padding: 30rpx;
  background-color: #f5f5f5;
}

.summary-card {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 40rpx 30rpx;
  border-radius: 20rpx;
  background-color: #fff;
  color: #333;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.summary-divider {
  width: 2rpx;
  height: 80rpx;
  background-color: #eee;
}

.amount-value {
  font-size: 56rpx;
  margin-bottom: 10rpx;
  color: #ff6b6b;
}

.amount-label {
  font-size: 26rpx;
  color: #666;
}

.borrow-list {
  flex: 1;
  background-color: #f5f5f5;
  padding: 0 30rpx 30rpx;
  overflow-y: auto;
  box-sizing: border-box;
  height: calc(100vh - 300rpx); /* 设置固定高度，减去顶部内容高度 */
}

.borrow-item {
  display: flex;
  align-items: center;
  padding: 24rpx 20rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  width: 100%;
}

.person-avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 35rpx;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  margin-right: 16rpx;
  flex-shrink: 0;
  overflow: hidden;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.borrow-info {
  width: 45%;
  overflow: hidden;
}

.person-name {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 8rpx;
  font-weight: 500;
}

.borrow-date {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.event-name {
  font-size: 24rpx;
  color: #666;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  display: inline-block;
}

.borrow-amount {
  flex: 1;
  text-align: right;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.amount-container {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.borrow-status {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  background-color: #f5f5f5;
}

.add-button {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #007AFF;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.2);
  z-index: 100;
}
</style>
  